package com.home.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.home.demo.dao.UserAndRoleDao;
import com.home.demo.entity.UserAndRoleEntity;
import com.home.demo.entity.dto.userAndRole.UserAndRoleDTO;
import com.home.demo.service.UserAndRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.stream.Collectors;


@Service("userAndRoleService")
public class UserAndRoleServiceImpl extends ServiceImpl<UserAndRoleDao, UserAndRoleEntity> implements UserAndRoleService {

    /**
     * 保存用户与角色的关联
     * @param userAndRole
     */
    @Override
    @Transactional
    public void saveInfo(UserAndRoleDTO userAndRole) {
        //删除原来已有的角色
        baseMapper.delete(
                new QueryWrapper<UserAndRoleEntity>()
                        .eq(userAndRole!=null&& StringUtils.hasText(userAndRole.getUserId())
                                ,"user_id"
                                ,userAndRole.getUserId()));

        this.saveBatch(Arrays.stream(userAndRole.getRoleIds()).map(roleId->{
            UserAndRoleEntity userAndRoleEntity = new UserAndRoleEntity();
            userAndRoleEntity.setUserId(userAndRole.getUserId());
            userAndRoleEntity.setUserId(roleId);
            return userAndRoleEntity;
        }).collect(Collectors.toList()));


    }

    /**
     * 删除角色与用户的关联
     * @param userAndRoleDTO
     */
    @Override
    public void removeByIdList(UserAndRoleDTO userAndRoleDTO) {
        if (!ObjectUtils.isEmpty(userAndRoleDTO)&&userAndRoleDTO.getRoleIds()!=null){
                baseMapper.delete(new QueryWrapper<UserAndRoleEntity>()
                        .in("role_id",userAndRoleDTO.getRoleIds())
                        .eq(StringUtils.hasText(userAndRoleDTO.getUserId()),"user_id",userAndRoleDTO.getUserId()));
        }
    }

}